package me.like.diandian.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.Toast;

import androidx.fragment.app.FragmentTransaction;

import com.igexin.sdk.PushManager;
import com.umeng.analytics.MobclickAgent;

import java.io.File;

import me.like.diandian.R;
import me.like.diandian.api.Api;
import me.like.diandian.base.BaseActivity;
import me.like.diandian.base.BaseConstant;
import me.like.diandian.databinding.ActivityMainBinding;
import me.like.diandian.fragment.HomeFragment;
import me.like.diandian.fragment.MeFragment;
import me.like.diandian.fragment.Tab2Fragment;
import me.like.diandian.requestbean.FrontAppVersionRequest;
import me.like.diandian.util.CommonUtils;
import me.like.diandian.util.RxUtils;
import me.like.diandian.util.updata.BGAUpgradeUtil;
import me.like.diandian.util.updata.DownloadingDialog;
import me.like.diandian.util.updata.UpdataDialog;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import rx.Subscriber;


public class MainActivity extends BaseActivity<ActivityMainBinding> {
    private FragmentTransaction ft;
    private HomeFragment homeFragment;
    private Tab2Fragment tab2Fragment;
    private MeFragment meFragment;
    int curIndex = 0;
    private Class userPushService = DemoPushService.class;
    private static final int RC_PERMISSION_DOWNLOAD = 1;
    /**
     * 删除文件权限请求码
     */
    private static final int RC_PERMISSION_DELETE = 2;
    private DownloadingDialog mDownloadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mImmersionBar.statusBarColor(R.color.white).init();
        setTabSelect(0);
        onClick(binding.lyMenu1, v -> {
            setTabSelect(0);
        });
        onClick(binding.lyMenu2, v -> {
            setTabSelect(1);
        });
        onClick(binding.lyMenu3, v -> {
            setTabSelect(2);
        });
        PushManager.getInstance().initialize(getApplicationContext(), userPushService);
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), DemoIntentService.class);

        Api.getInstance().getService().queryAppVersionInfo(new FrontAppVersionRequest(BaseConstant.APPCHANNELID)).compose(RxUtils.applySchedulerAndAllFilter(this))
                .subscribe(data -> {
                    if (data.getData() != null) {
                        int version = data.getData().getVersion();
                        int oldData = CommonUtils.getVersionCode();
                        int hasForcedUpgrade = data.getData().getIsForceUpdate();
                        if (version > oldData) {
                            boolean isMustUpdate;
                            if ("1".equals(hasForcedUpgrade)) {
                                isMustUpdate = false;
                            } else {
                                isMustUpdate = true;
                            }
                            new UpdataDialog(this, getString(R.string.app_name) + data.getData().getAppName(), isMustUpdate) {
                                @Override
                                public void onOkClick() {
                                    super.onOkClick();
//                                    deleteApkFile();
                                    downloadApkFile(data.getData().getAppDownUrl(), data.getData().getVersion() + "");
                                }
                            }.show();
                        }
                    }

                }, Throwable::printStackTrace);
        BGAUpgradeUtil.getDownloadProgressEventObservable()
//                .compose(this.<BGADownloadProgressEvent>bindToLifecycle())
                .subscribe((downloadProgressEvent) -> {
                    if (mDownloadingDialog != null && mDownloadingDialog.isShowing() && downloadProgressEvent.isNotDownloadFinished()) {
                        mDownloadingDialog.setProgress(downloadProgressEvent.getProgress(), downloadProgressEvent.getTotal());
                    }
                });
        setstateBar(true);

    }


    /**
     * 删除之前升级时下载的老的 apk 文件
     */
    @AfterPermissionGranted(RC_PERMISSION_DELETE)
    public void deleteApkFile() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // 删除之前升级时下载的老的 apk 文件
            BGAUpgradeUtil.deleteOldApk();
        } else {
            EasyPermissions.requestPermissions(this, "使用 BGAUpdateDemo 需要授权读写外部存储权限!", RC_PERMISSION_DELETE, perms);
        }
    }


    public void toTab2(int tab) {
        if(tab2Fragment==null){
            setTabSelect(1);
            tab2Fragment.setCurent(tab);
        }else {
            setTabSelect(1);
            tab2Fragment.setCurent2(tab);
        }


    }

    /**
     * 下载新版 apk 文件
     */
    @AfterPermissionGranted(RC_PERMISSION_DOWNLOAD)
    public void downloadApkFile(String mApkUrl, String mNewVersion) {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // 如果新版 apk 文件已经下载过了，直接 return，此时不需要开发者调用安装 apk 文件的方法，在 isApkFileDownloaded 里已经调用了安装」
            if (BGAUpgradeUtil.isApkFileDownloaded(mNewVersion)) {
                return;
            }

            // 下载新版 apk 文件
            BGAUpgradeUtil.downloadApkFile(mApkUrl, mNewVersion)
                    .subscribe(new Subscriber<File>() {
                        @Override
                        public void onStart() {
                            //http://blog.csdn.net/jdsjlzx/article/details/51868640
                            request(1); //要在onStart中通知被观察者先发送一个事件
                            showDownloadingDialog();
                        }

                        @Override
                        public void onCompleted() {
                            dismissDownloadingDialog();
                        }

                        @Override
                        public void onError(Throwable e) {
                            dismissDownloadingDialog();
                        }

                        @Override
                        public void onNext(File apkFile) {
                            request(1); //处理完毕之后，在通知被观察者发送下一个事件
                            if (apkFile != null) {
                                BGAUpgradeUtil.installApk(apkFile);
                            }
                            finish();
                        }
                    });
        } else {
            EasyPermissions.requestPermissions(this, "使用 BGAUpdateDemo 需要授权读写外部存储权限!", RC_PERMISSION_DOWNLOAD, perms);
        }
    }

    /**
     * 显示下载对话框
     */
    protected void showDownloadingDialog() {
        if (mDownloadingDialog == null) {
            mDownloadingDialog = new DownloadingDialog(this);
        }
        mDownloadingDialog.show();
    }

    /**
     * 隐藏下载对话框
     */
    protected void dismissDownloadingDialog() {
        if (mDownloadingDialog != null) {
            mDownloadingDialog.dismiss();
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    private void setTabSelect(int index) {
        ft = getSupportFragmentManager().beginTransaction();
        hideFragments(ft);
        curIndex = index;
        switch (index) {
            case 0:
                if (homeFragment == null) {
                    homeFragment = new HomeFragment();
                    ft.add(R.id.fragment, homeFragment);
                } else {
                    ft.show(homeFragment);

                }
                binding.lyMenu1.setSelected(true);
                binding.lyMenu2.setSelected(false);
                binding.lyMenu3.setSelected(false);
                break;
            case 1:
                if (tab2Fragment == null) {
                    tab2Fragment = new Tab2Fragment();
                    ft.add(R.id.fragment, tab2Fragment);
                } else {
                    ft.show(tab2Fragment);
                }

                binding.lyMenu1.setSelected(false);
                binding.lyMenu2.setSelected(true);
                binding.lyMenu3.setSelected(false);
                break;
            case 2:
                if (meFragment == null) {
                    meFragment = new MeFragment();
                    ft.add(R.id.fragment, meFragment);
                } else {
                    ft.show(meFragment);
                }

                binding.lyMenu1.setSelected(false);
                binding.lyMenu2.setSelected(false);
                binding.lyMenu3.setSelected(true);
                break;
            default:
                break;

        }
        ft.commitAllowingStateLoss();

    }

    private void hideFragments(FragmentTransaction ft) {
        if (homeFragment != null) {
            ft.hide(homeFragment);
        }
        if (tab2Fragment != null) {
            ft.hide(tab2Fragment);
        }
        if (meFragment != null) {
            ft.hide(meFragment);
        }
    }

    public static void launch(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    private long oldTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if ((System.currentTimeMillis() - oldTime) > 2000) {
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                oldTime = System.currentTimeMillis();
            } else {
                MobclickAgent.onKillProcess(MainActivity.this);
                finish();
//                System.exit(0);
                super.onBackPressed();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
